const app = getApp()
const {upTime} = require('/util/public')
Page({
    data: {
        types:[
            {title:'全部',state:-2,order:[],totalResult:null,page:1},
            {title:'待付款',state:1,order:[],totalResult:null,page:1},
            {title:'待审核',state:2,order:[],totalResult:null,page:1},
            {title:'待签署',state:40,order:[],totalResult:null,page:1},
            {title:'待发货',state:3,order:[],totalResult:null,page:1},
            {title:'待收货',state:4,order:[],totalResult:null,page:1},
            {title:'待归还',state:5,order:[],totalResult:null,page:1},
            {title:'已完成',state:7,order:[],totalResult:null,page:1},
            {title:'已关闭',state:12,order:[],totalResult:null,page:1},
            {title:'申请取消',state:14,order:[],totalResult:null,page:1}
        ],
        activeTab: 0,
        status: ['', "待付款", "待审核", "待发货", "待收货", "待归还", "归还中", "交易完成", "完结订单", "订单关闭（用户）", "订单关闭（系统）", "订单关闭（商家）", "已完成", '即将到期', '申请取消'],

        totalPage: null,
        items: [
          { name: '计划有变', value: '计划有变', checked: true },
          { name: '预收租金/补押金', value: '预收租金/补押金' },
          { name: '运费问题', value: '运费问题' },
          { name: '审核时间过长', value: '审核时间过长' },
          { name: '商家没货/服务态度问题', value: '商家没货/服务态度问题' },
        ],
        popShow: false,
        causeCon: '计划有变',
        cancelId: '',
        cancelStatus: ''
    },
    onLoad(query) {
        if(query.param){
            let index = JSON.parse(query.param)
            this.handleTabClick({index:index,tabsName:'activeTab'})
        }else {
            let index = 0;
            this.handleTabClick({index:index,tabsName:'activeTab'})
        };
        app._init_(this);
    },

    // tabs
    handleTabClick({ index=0, tabsName }){
        this.setData({
            [tabsName]: index,
        });
        const types = this.data.types;
        if(types[index].totalResult==null){
            this.get_meg()
        }
    },

    // 获取数据
    get_meg() {
        this.setData({ show: true });
        const types = this.data.types;
        let data = {
            status: types[this.data.activeTab].state,
            page: types[this.data.activeTab].page,
            rows: 10,
        } 
        app.order.page(data)
        .then(res=>{
            console.log(res)
            res.data.list.forEach((item)=>{
                
                item.paramsOld = item.params;
                item.params = JSON.parse(item.params);
                item.params.saleQuantity = item.params.numberDevices?item.params.numberDevices:1;

                item.createtime = upTime("%Y-%M-%D %h:%m:%h", item.createtime);
                item.starttime = item.starttime ? upTime("%Y-%M-%D", item.starttime) : '';
                item.endtime = item.endtime ? upTime("%Y-%M-%D", item.endtime) : '';
                if(item.status==4 && item.productOrderShipment!=null){
                    item.flowOne = {
                        id:item.id,
                        receiverPhone:item.phone.slice(-4, item.phone.length),
                        com:item.productOrderShipment.company,
                        no:item.productOrderShipment.number,
                    }
                }else if(item.status==6 && item.productOrderRecycle!=null){
                    item.flowOne = {
                        id:item.id,
                        receiverPhone:item.shopsVo.phone.slice(-4, item.phone.length),
                        com:item.productOrderRecycle.company,
                        no:item.productOrderRecycle.number,
                    }
                } 
                else {
                    item.flowOne = null
                }
            })
            types[this.data.activeTab].order = [...types[this.data.activeTab].order,...res.data.list]
            types[this.data.activeTab].totalResult = res.data.totalResult
            this.setData({types})
            setTimeout(() => {
                this.setData({ show: false });
            }, 200)
        })
    },

    // btn 订单按钮
    //   联系商家
    makePhoneCall(e) {
        // console.log(e.target.dataset.phone)
        let phone = e.target.dataset.phone;
        my.makePhoneCall({ number: phone });
    },

    // alipays编码
    getSignUrl(aliSchema) {
        if(!aliSchema){return  ''}
        const querys = aliSchema.split('?')[1].split('&');
        const signUrlKeyValue = querys.find((item) => item.includes('query=')).replace('query=', '');
        const encodedSignUrl = decodeURIComponent(signUrlKeyValue).replace('signUrl=', '');
        return encodedSignUrl
    },



     //代扣合同跳转长
     goExteriorPage(e){

      // my.requestSubscribeMessage({
      //   entityIds: ['1409d0ab343147a8bc17cdb1f6b2843d', '4ee18d5b94fa488591a948a617715734'],
      //   complete: (res) => {
      //     let mylContractSignUrl = e.target.dataset.data;
      //     let signUrl = this.getSignUrl(mylContractSignUrl);

      //     my.navigateToMiniProgram({
      //         appId: '2021001152620480',
      //         path:`pages/signH5/index?signUrl=${signUrl}`,
      //         success: (res) => {
      //           console.log(JSON.stringify(res))
      //         },
      //         fail: (res) => {
      //           console.log(JSON.stringify(res));
      //           my.alert({
      //             title: JSON.stringify(res),
      //           });
      //         }
      //     });
      //   }
      // });

      console.log("签署代扣",e)
      
        
      
      my.ap.openURL({
        url: e.currentTarget.dataset.data, // 请将 url 替换为后台加白过的跳转地址
        success: (res) => {
            console.log('openURL success', res)
        },
        fail: (err) => {
            console.log('openURL success', err)
        }
    });
    

      
      

    },
    

    // 取消原因选择
    radioChange(e){
      let con = e.detail.value;
      this.setData({
        causeCon: con
      })
    },

    // 关闭取消弹窗
    popCancelBtn(){
      this.setData({
        cancelId: '',
        cancelStatus: '',
        causeCon: '计划有变',
        popShow: false
      })
    },
    // 确认取消
    popAffirmBtn(){
      console.log(this.data.causeCon,this.data.cancelId,this.data.cancelStatus,'原因');

      if (this.data.cancelStatus == 1) {
          app.order.canOrder(this.data.cancelId,{cont: this.data.causeCon})
          .then((res)=>{
              my.alert({
                  title: "取消成功",
                  success: () => {
                      this.popCancelBtn();
                      this.resetOrder();
                  }
              });
          })
      } else if (this.data.cancelStatus == 2) {
          app.order.requestCanOrder(this.data.cancelId,{cont: this.data.causeCon})
          .then((res)=>{
              console.log(res)
              my.alert({
                  title: "申请成功",
                  success: () => {
                      this.popCancelBtn();
                      this.resetOrder();
                  }
              });
              
          })
      }
    },

    // 关闭订单, 申请取消
    onCancel(e) {
        // console.log(e.target.dataset.item)
        let id = e.target.dataset.item.id;
        let status = e.target.dataset.item.status;

        console.log(e,'滴滴');

        this.setData({
          cancelId: id,
          cancelStatus: status,
          popShow: true
        })

        // my.prompt({
        //     title: '申请取消',
        //     message: '请输入取消原因，否则无法为你取消',
        //     placeholder: '请输入取消原因',
        //     okButtonText: '确定',
        //     cancelButtonText: '取消',
        //     success: (result) => {
        //         console.log(result)
        //         if (!result.ok) {
        //             return
        //         }
        //         if (result.inputValue) {
        //             if (status == 1) {
        //                 app.order.canOrder(id,{cont: result.inputValue})
        //                 .then((res)=>{
        //                     my.alert({
        //                         title: "取消成功",
        //                         success: () => {
        //                             this.resetOrder()
        //                         }
        //                     });
        //                 })
        //             } else if (status == 2) {
        //                 app.order.canOrder(id,{cont: result.inputValue})
        //                 .then((res)=>{
        //                     console.log(res)
        //                     my.alert({
        //                         title: "申请成功",
        //                         success: () => {
        //                             this.resetOrder()
        //                         }
        //                     });
                            
        //                 })
        //             }
        //         } else {
        //             my.showToast({
        //                 type: 'exception',
        //                 content: '请输入取消原因',
        //             });
        //         }
        //     },
        // });
    },
    // 撤销申请
    noCancel(e){
        let cancelRequests = e.target.dataset.item.productOrderCancelRequests
        let id = cancelRequests[cancelRequests.length-1].id
        my.confirm({
            title: '温馨提示',
            content: '是否撤回订单取消申请',
            confirmButtonText: '立即撤回',
            cancelButtonText: '暂不撤回',
            success: (result) => {
                if (result.confirm) {
                    app.order.repeal(id)
                    .then(red=>{
                        if(res.code==200) {
                            my.alert({
                                title: "撤回成功",
                                success: () => {
                                    this.resetOrder()
                                }

                            });
                        }
                    })
                }
            },
        });
    },

     // 冻结
    onBuy(e) {
        let that = this
        const data = e.target.dataset.data;
        app.order.freeze(data.id)
        .then(pay=>{
            my.tradePay({
                orderStr: pay.data, // 完整的支付参数拼接成的字符串，从服务端获取
                success: (res) => {
                    console.log(res)
                    if (res.resultCode == 9000) {
                        my.alert({
                            content: "支付成功",
                        });
                        this.resetOrder()
                    } 
                },
                fail: (res) => {
                    my.alert({
                        content: res.memo,
                    });
                }
            });
        })
    },
    // 支付
    onReplenish(e) {
        let that = this
        let oid = e.target.dataset.data.productOrderRecordVoList[0].oid
        let id = e.target.dataset.data.productOrderRecordVoList[0].id
        console.log(123,oid,id)
        app.order.alipay(oid,id)
        .then(res=>{
            my.tradePay({
                tradeNO: res.data,
                success: function (res) {
                    // console.log(res)
                    if (res.resultCode == 9000) {
                        my.alert({
                            content: "支付成功",
                        });
                        this.resetOrder()
                    } else {
                        my.alert({
                            content: res.memo,
                        });
                    }
                },
                
            });
        })
    },
     // 确认收货
    ConfirmReceipt(e) {
        let id = e.target.dataset.id
        app.order.receiving(id)
        .then(res=>{
            if (res.code == 200) {
                my.alert({
                    content: "提交成功",
                    success: () => {
                        this.resetOrder()
                    }
                })
            } else {
                my.alert({
                    content: res.msg
                })
            }
        })
    },
    // 跳转
    navigateTo(e){
      console.log(e)
        app.navigateTo(e)
    },

    // 重置订单列表
    resetOrder(){
        const types = this.data.types;
        const tabIndex = this.data.activeTab;
        types[tabIndex].order = [];
        types[tabIndex].totalResult =null;
        this.setData({types});
        this.onLoad({param:this.data.activeTab});
    },

    // 下拉刷新
    onPullDownRefresh() {
        this.resetOrder();
        this.popCancelBtn();
        setTimeout(() => {
            my.stopPullDownRefresh({
                complete(res) {
                }
            })
        }, 1000)
    },
    stopPullDownRefresh() {
        my.stopPullDownRefresh({
            complete(res) {
                // console.log(res, new Date())
            }
        })
    },
    //   下拉加载
    onReachBottom() {
        const that = this
        const types = this.data.types;
        const tabIndex = this.data.activeTab
        try {
            // 判断是否还有数据需要加载
            if (types[tabIndex].order.length < types[tabIndex].totalResult) {
                types[tabIndex].page++
                that.get_meg();
            }
        } catch (e) {}
    },
});
